package com.sl.hx.shop.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;


import com.jaeger.library.StatusBarUtil;
import com.sl.hx.shop.R;
import com.sl.hx.shop.utils.ActivityManager;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * Activity基类
 * Created by hwg on 2017/12/20.
 */

public abstract class BaseActivity<V, T extends BasePresenter<V>> extends RxAppCompatActivity implements BaseView{

    protected Context mContext ;

    protected T mPresenter ;

    private Unbinder unbinder;
    /**
     * 绑定布局
     * @return
     */
    protected abstract @LayoutRes
    int getLayoutId();

    /**
     * 创建Presenter
     * @return
     */
    protected abstract T createPresenter();

    protected abstract void initView();

    protected abstract void initData();

    @Override
    public <T> LifecycleTransformer<T> bindToLife(ActivityEvent activityEvent) {
        return this.<T>bindUntilEvent(activityEvent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        ActivityManager.getAppInstance().addActivity(this);//将当前activity添加进入管理栈
        /**
         * 允许为空，不是所有页面都是需要实现mvp模式的
         * 不为空时，为view创建一个弱引用
         */
        mPresenter = createPresenter() ;
        if (mPresenter != null){
            mPresenter.attachView((V) this);
        }


        if (getLayoutId() != 0){
            setContentView(getLayoutId());
            //ButterKnife绑定布局
            unbinder=ButterKnife.bind(this) ;
        }
        //设置沉浸式
        //setStatusBar();
        initView();
        initData();

    }

    protected void setStatusBar() {
        StatusBarUtil.setColor(this, getResources().getColor(R.color.colorPrimary));
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mPresenter != null){
            mPresenter.attachView((V) this);
        }
    }

    @Override
    protected void onDestroy() {
        ActivityManager.getAppInstance().removeActivity(this);//将当前activity移除管理栈
        super.onDestroy();
        //清空presenter对view的引用
        if (mPresenter != null){
            mPresenter.detachView();
        }
        unbinder.unbind();
    }

    /**
     * 不带参数，从Activity跳转到指定Activity
     *
     * @param activity
     */
    protected void toActivity(Class<?> activity){
        startActivity(new Intent(this , activity));
    }

}
